@file:Suppress("VARIABLE_WITH_REDUNDANT_INITIALIZER", "DEPRECATION")

package com.csjbot.weedle_auto.file.constants_util

import android.content.Context
import android.os.Environment
import android.os.StatFs
import android.support.v7.app.AlertDialog
import android.view.View
import com.csjbot.weedle_auto.file.SaveFileStationListener
import com.csjbot.weedle_auto.util.Csjlogger
import java.io.*
import java.util.*

/**
 * Created by sunxy on 2017/3/21.
 */

object FileUtil {
    /**
     * 获取内置SD卡路径
     *
     * @return
     */
    val innerSDCardPath: String
        get() = Environment.getExternalStorageDirectory().path

    /**
     * 创建文件
     *
     * @param filePath
     * @return
     */
    fun createFolder(filePath: String): File? {
        var file: File? = null
        if (isExistSDCard) {
            file = File(filePath)
            if (!file.exists()) {
                file.mkdirs()
            }
        }
        return file
    }

    fun getFolderList(filePath: String): List<File> {
        val dir = Environment.getExternalStorageDirectory()
        val path2 = File(dir.toString() + File.separator + filePath)
        Csjlogger.info("chenqi getPath {}" + path2)
        val li = ArrayList<File>()
        for (i in 0..path2.listFiles().size - 1) {
            li.add(path2.listFiles()[i])
        }
        return li
    }

    //        File dir = Environment.getExternalStorageDirectory().;
    val folderList: List<File>
        get() {
            val path2 = File(innerSDCardPath)
            val li = ArrayList<File>()
            for (i in 0..path2.listFiles().size - 1) {
                li.add(path2.listFiles()[i])
            }
            return li
        }


    fun getAllPath(filePath: File): String {
        return if (filePath.isDirectory) {
            filePath.absolutePath
        } else ""
    }

    fun getName(filePath: File): String {
        return if (filePath.isDirectory) {
            filePath.name
        } else ""
    }


    /**
     * 确定是文件夹还是文件
     *
     * @param filePath
     * @return
     */
    fun isFolder(filePath: String): Boolean {
        val file = File(filePath)
        var isFolder = false
        if (file.exists()) {
            isFolder = file.isDirectory
        }
        return isFolder
    }

    //    public static String getFolderPath(String filePath){
    //
    //    }

    /**
     * 删除单个文件
     *
     * @param sPath 被删除文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    fun deleteFile(sPath: String): Boolean {
        var flag = false
        val file = File(sPath)
        // 路径为文件且不为空则进行删除
        if (file.isFile && file.exists()) {
            file.delete()
            flag = true
        }
        return flag
    }

    /**
     * 异步删除文件
     *
     * @param sPath
     */
    fun asyncDeleteFile(sPath: String) {
        Thread(Runnable { deleteFile(sPath) }).start()
    }

    /**
     * 复制文件
     */
    @Throws(IOException::class)
    fun copyFile(sourceFile: File, targetFile: File) {
        //新建文件输入流并对它进行缓冲   
        val input = FileInputStream(sourceFile)
        val inBuff = BufferedInputStream(input)
        //新建文件输出流并对它进行缓冲   
        val output = FileOutputStream(targetFile)
        val outBuff = BufferedOutputStream(output)
        //缓冲数组   
        val b = ByteArray(1024 * 5)

        while ((inBuff.read(b)) != -1) {
            outBuff.write(b, 0, (inBuff.read(b)))
        }
        //刷新此缓冲的输出流   
        outBuff.flush()
        //关闭流   
        inBuff.close()
        outBuff.close()
        output.close()
        input.close()
    }

    /**
     * 复制文件夹
     */
    @Throws(IOException::class)
    fun copyDirectiory(sourceDir: String, targetDir: String) {
        //新建目标目录   
        File(targetDir).mkdirs()
        //获取源文件夹当前下的文件或目录   
        val file = File(sourceDir).listFiles()
        for (i in file.indices) {
            if (file[i].isFile) {
                //源文件   
                val sourceFile = file[i]
                //目标文件   
                val targetFile = File(File(targetDir).absolutePath + File.separator + file[i].name)
                copyFile(sourceFile, targetFile)
            }
            if (file[i].isDirectory) {
                //准备复制的源文件夹
                val dir1 = sourceDir + "/" + file[i].name
                //准备复制的目标文件夹
                val dir2 = targetDir + "/" + file[i].name
                copyDirectiory(dir1, dir2)
            }
        }
    }

    /**
     * 保存字符串为txt
     *
     * @param toSaveString
     * @param filePath
     */
    fun saveFile(toSaveString: String, filePath: File): Boolean {
        try {

            if (!filePath.exists()) {
                val dir = File(filePath.parent)
                dir.mkdirs()
                filePath.createNewFile()
            }
            val outStream = FileOutputStream(filePath)
            outStream.write(toSaveString.toByteArray())
            outStream.close()
        } catch (e: FileNotFoundException) {
            Csjlogger.info("chenqi FileNotFoundException")
            return false
        } catch (e: IOException) {
            Csjlogger.info("chenqi IOException")
            e.printStackTrace()
            return false
        }

        return true
    }

    //    public void saveFile(String info,Context context){
    ////        File file = new File(context.getFilesDir(),"")
    //    }

    /**
     * 通过文件路径读取文件
     *
     * @param filePath
     */
    fun ReadFile(filePath: String): String? {
        var str = ""
        try {
            val readFile = File(filePath)
            if (!readFile.exists()) {
                return null
            }
            val inStream = FileInputStream(readFile)
            val stream = ByteArrayOutputStream()
            val buffer = ByteArray(1024)
            while ((inStream.read(buffer)) != -1) {
                stream.write(buffer, 0, (inStream.read(buffer)))
            }

            str = stream.toString()
            stream.close()
            inStream.close()
            return str
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            return null
        } catch (e: IOException) {
            e.printStackTrace()
            return null
        }

    }

    /**
     * 是否存在SD卡
     *
     * @return
     */
    val isExistSDCard: Boolean
        get() = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED

    /**
     * 是否移除SD卡
     *
     * @return
     */
    val isSDCardRemove: Boolean
        get() = Environment.getExternalStorageState() == Environment.MEDIA_REMOVED

    /**
     * SD卡总容量
     *
     * @return
     */
    //取得SD卡文件路径
    //获取单个数据块的大小(Byte)
    //获取所有数据块数
    //返回SD卡大小
    //单位MB 
    val sdAllSize: Long
        get() {
            val path = Environment.getExternalStorageDirectory()
            val sf = StatFs(path.path)
            val blockSize = sf.blockSizeLong
            val allBlocks = sf.blockCountLong
            return allBlocks * blockSize / 1024 / 1024
        }

    /**
     * SD卡剩余容量
     *
     * @return
     */
    //取得SD卡文件路径
    //获取单个数据块的大小(Byte)
    //获取所有数据块数
    //返回SD卡大小
    //单位MB 
    val sdFreeSize: Long
        get() {
            val path = Environment.getExternalStorageDirectory()
            val sf = StatFs(path.path)
            val blockSize = sf.blockSizeLong
            val allBlocks = sf.freeBlocksLong
            return allBlocks * blockSize / 1024 / 1024
        }

    /**
     *   File sdCardDir = Environment.getExternalStorageDirectory();//获取SDCard目录
     *   File saveFile = new File(sdCardDir, "ljq.txt");
     *   FileOutputStream outStream = new FileOutputStream(saveFile);
     *   outStream.write("abc".getBytes());
     *   outStream.close();
     */


    fun saveFileToSave(fileName: String, path: File, msg: String, saveFileStationListener: SaveFileStationListener) {
        val saveFile = File(path, fileName)
        val outStream: FileOutputStream
        try {
            if (!saveFile.exists()) {
                val dir = File(saveFile.parent)
                dir.mkdirs()
                saveFile.createNewFile()
            } else {
                saveFileStationListener.FileIsExists()
            }
            outStream = FileOutputStream(saveFile)
            outStream.write(msg.toByteArray())
            outStream.close()
            if (saveFile.exists()) {
                saveFileStationListener.SaveSuccess()
            }
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            saveFileStationListener.FileNotFound()
            return
        } catch (e: IOException) {
            e.printStackTrace()
            saveFileStationListener.IOEError()
            return
        }

    }

    /**
     * SD卡剩余容量 Byte
     *
     * @return
     */
    val sdFreeByteSize: Long
        get() {
            val path = Environment.getExternalStorageDirectory()
            val sf = StatFs(path.path)
            val blockSize = sf.blockSizeLong
            val allBlocks = sf.freeBlocksLong
            return allBlocks * blockSize
        }

    fun newPackage(context: Context, folder: String) {
        val mkdirs = Environment.getExternalStorageDirectory().toString() + folder
        val file = File(mkdirs)
        val builder = AlertDialog.Builder(context)
        if (file.exists()) {
            builder.setMessage("文件夹已经存在").show()
        } else {
            file.mkdirs()
            builder.setMessage("新建成功").show()
        }
    }


    /**
     * 判断机子是否被root过了
     */
    private val kSystemRootStateUnknow = -1
    private val kSystemRootStateDisable = 0
    private val kSystemRootStateEnable = 1
    private var systemRootState = kSystemRootStateUnknow

    val isRootSystem: Boolean
        get() {
            if (systemRootState == kSystemRootStateEnable) {
                return true
            } else if (systemRootState == kSystemRootStateDisable) {

                return false
            }
            var f: File? = null
            val kSuSearchPaths = arrayOf("/system/bin/", "/system/xbin/", "/system/sbin/", "/sbin/", "/vendor/bin/")
            try {
                for (i in kSuSearchPaths.indices) {
                    f = File(kSuSearchPaths[i] + "su")
                    if (f.exists()) {
                        systemRootState = kSystemRootStateEnable
                        return true
                    }
                }
            } catch (e: Exception) {
            }

            systemRootState = kSystemRootStateDisable
            return false
        }

}
